import React from 'react';
import { withRouter, router } from 'umi';
import { message, Form, Input, Icon, Popover, Spin, Row, Col } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import {
    InterviewBoxPcB,
    InterviewDetail,
    ButtonPc as Button,
    InputPassword
} from '@/pages/RecruitEmail/pc/components';
import { useLogin } from '@/pages/RecruitEmail/hooks';
import { updatePassword, getLoginInfo, getVerificationCode } from '@/pages/RecruitEmail/service/interview';
import cn from 'classnames';
import pic from '@/pages/RecruitEmail/images/interview-bg-refuse.png';
import picLogin from '@/pages/RecruitEmail/images/interview-bg-new.png';
import styles from './index.less';

const Login = ({ form, location }) => {
    const { query } = location;

    const { getFieldDecorator } = form;
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [title, setTitle] = React.useState('');
    const [content, setContent] = React.useState('');
    const [authCode, setAuthCode] = React.useState('');
    const [randomNumber, setRandomNumber] = React.useState('');
    const [codeLoading, setCodeLoading] = React.useState(false);

    const { data, loading } = useRequest(() => getLoginInfo(query?.id), {
        initialData: null,
        ...defaultFormatResult
    });

    // 获取验证码
    const getAuthCode = () => {
        setCodeLoading(true);
        // 生成随机数
        const genID = length =>
            Number(
                Math.random()
                    .toString()
                    .substr(3, length) + Date.now()
            ).toString(36);
        const random = genID(3);

        getVerificationCode(random).then(res => {
            setCodeLoading(false);
            if (res?.code === 10000) {
                setAuthCode(res?.data);
                setRandomNumber(random);
            } else {
                message.error(res?.msg);
            }
        });
    };

    const { needAuthCode, handleLogin, handleloading } = useLogin(query, getAuthCode);
    // React.useEffect(() => {
    //     if (needAuthCode) {
    //         getAuthCode();
    //     }
    // }, [needAuthCode]);

    React.useEffect(() => {
        if (data?.modifyPwdSafetyCode) {
            setTitle('请设置密码，登录并完善《应聘登记表》');
            setContent('微微科技为你开通了候选人帐号');
        } else {
            setTitle(data?.talentName ? `你好，${data?.talentName}！` : '');
            setContent('');
        }
    }, [data]);
    const list = [
        {
            key: '用户名称',
            showIcon: true,
            iconType: 'countpeople_o',
            value: data?.talentName || '--'
        },
        {
            key: '手机号',
            showIcon: true,
            iconType: 'infos_phone_icon_default',
            value: data?.talentPhone || '--'
        },
        {
            key: '账号邮箱',
            showIcon: true,
            iconType: 'infos_namecard_icon_default1',
            value: data?.talentEmail || '--'
        }
    ];

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                setSubmitLoading(true);
                if (data?.modifyPwdSafetyCode) {
                    updatePassword({
                        key: data?.modifyPwdSafetyCode,
                        password: values.password
                    })
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                // form.resetFields();
                                // getInfo();
                                // history.push({
                                //     pathname: '/recruitment/login',
                                //     query
                                // });
                                handleLogin({
                                    talentEmail: data?.talentEmail || '',
                                    password: values.password,
                                    verificationKey: randomNumber,
                                    verificationValue: values?.verificationValue
                                });
                            } else {
                                message.error(msg);
                                setSubmitLoading(false);
                            }
                        })
                        .catch(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    handleLogin({
                        talentEmail: values?.talentEmail || '',
                        password: values.password,
                        verificationKey: randomNumber,
                        verificationValue: values?.verificationValue
                    });
                }
            }
        });
    };

    // React.useEffect(() => {
    //     if (query?.candidateLinkId) {
    //         fetchDetail();
    //     }
    // }, [query]);

    const detailStyle = {
        keyStyle: {
            color: '#BCC1CD',
            fontWeight: 500
        },
        valueStyle: {
            color: '#2A2F3C'
        }
    };

    const renderLeftView = () => (
        <div
            style={{
                width: 392,
                margin: '196px auto',

                boxSizing: 'border-box'
            }}
        >
            <div className={styles.resultTitle}>账户信息</div>
            <div className={styles.resultDesc}>该帐号也将在后续应聘过程中使用，请您妥善保管</div>
            <div className={cn(styles.detailCon)}>
                <InterviewDetail
                    dataSource={list}
                    flexStyle={{
                        flexDirection: 'row',
                        flexWrap: 'wrap',
                        justContent: 'space-between'
                    }}
                    keyStyle={{
                        fontWeight: 400,
                        height: '22px',
                        fontSize: '14px',
                        fontFamily: 'PingFangSC-Regular, PingFang SC',
                        color: 'rgba(0,0,0,0.45)',
                        lineHeight: '22px'
                    }}
                    valueStyle={{
                        height: '26px',
                        fontSize: '18px',
                        fontFamily: 'PingFangSC-Regular, PingFang SC',
                        fontWeight: 400,
                        color: 'rgba(0,0,0,0.85)',
                        lineHeight: '26px'
                    }}
                />
            </div>
        </div>
    );
    const renderRightView = () => (
        <div style={{ width: 392, boxSizing: 'borderBox', margin: '0 auto' }}>
            <div style={{ marginTop: '110px' }}>
                <InterviewDetail
                    style={{ padding: 0, margin: 0 }}
                    dataSource={[
                        {
                            key: '设置密码',
                            showIcon: false,
                            render: (
                                <span
                                    style={{
                                        display: 'block',
                                        marginBottom: '8px',
                                        height: '24px',
                                        lineHeight: '24px',
                                        fontSize: 16,
                                        fontFamily: 'PingFangSC-Regular, PingFang SC',
                                        fontWeight: 400,
                                        color: 'rgba(0,0,0,0.65)'
                                    }}
                                >
                                    设置密码
                                </span>
                            ),
                            value: (
                                <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                    <Popover
                                        placement="right"
                                        content={
                                            <div
                                                style={{
                                                    width: 210,
                                                    boxSizing: 'border-box',
                                                    display: 'flex'
                                                }}
                                            >
                                                <Icon
                                                    type="close-circle"
                                                    theme="filled"
                                                    style={{
                                                        marginRight: '4px',
                                                        color: '#F55656',
                                                        paddingTop: '4px'
                                                    }}
                                                />
                                                <div>
                                                    {form.getFieldError('password')
                                                        ? form.getFieldError('password')[0]
                                                        : ''}
                                                </div>
                                            </div>
                                        }
                                        visible={!!form.getFieldError('password')}
                                    >
                                        {getFieldDecorator('password', {
                                            rules: [
                                                {
                                                    required: true,
                                                    whiteSpace: true,
                                                    message: '请输入密码'
                                                },
                                                {
                                                    validator(rule, value, callback) {
                                                        const regex = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).*$/;
                                                        if (value) {
                                                            const tempValue = value.trim();
                                                            if (
                                                                tempValue.length >= 8 &&
                                                                tempValue.length <= 20 &&
                                                                regex.test(value)
                                                            ) {
                                                                callback();
                                                            } else {
                                                                callback(
                                                                    '长度为8-20个字符，需同时包含大小写字母及数字'
                                                                );
                                                            }
                                                        }
                                                        callback();
                                                    }
                                                }
                                            ]
                                        })(
                                            <InputPassword
                                                placeholder="请输入密码"
                                                minLength={8}
                                                maxLength={20}
                                                allowClear
                                            />
                                        )}
                                    </Popover>
                                </Form.Item>
                            )
                        }
                    ]}
                />
            </div>
            <InterviewDetail
                style={{ padding: 0, margin: 0 }}
                dataSource={[
                    {
                        key: '确认密码',
                        render: (
                            <span
                                style={{
                                    height: '24px',
                                    lineHeight: '24px',
                                    fontSize: 16,
                                    fontFamily: 'PingFangSC-Regular, PingFang SC',
                                    fontWeight: 400,
                                    color: 'rgba(0,0,0,0.65)',
                                    display: 'block',
                                    marginBottom: '8px'
                                }}
                            >
                                确认密码
                            </span>
                        ),
                        value: (
                            <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                <Popover
                                    placement="right"
                                    content={
                                        <div
                                            style={{
                                                width: 210,
                                                boxSizing: 'border-box',
                                                display: 'flex'
                                            }}
                                        >
                                            <Icon
                                                type="close-circle"
                                                theme="filled"
                                                style={{
                                                    marginRight: '4px',
                                                    color: '#F55656',
                                                    paddingTop: '4px'
                                                }}
                                            />
                                            <div>
                                                {form.getFieldError('password2')
                                                    ? form.getFieldError('password2')[0]
                                                    : ''}
                                            </div>
                                        </div>
                                    }
                                    visible={!!form.getFieldError('password2')}
                                >
                                    {getFieldDecorator('password2', {
                                        rules: [
                                            {
                                                required: true,
                                                whiteSpace: true,
                                                message: '请输入确认密码'
                                            },
                                            {
                                                validator(rule, value, callback) {
                                                    if (value) {
                                                        const tempValue = value.trim();
                                                        const password = form.getFieldValue('password').trim();
                                                        if (tempValue === password) {
                                                            callback();
                                                        } else {
                                                            callback('两次输入的密码不相同');
                                                        }
                                                    }
                                                    callback();
                                                }
                                            }
                                        ]
                                    })(
                                        <InputPassword
                                            placeholder="请输入密码"
                                            minLength={8}
                                            maxLength={20}
                                            allowClear
                                        />
                                    )}
                                </Popover>
                            </Form.Item>
                        )
                    }
                ]}
                {...detailStyle}
            />
            <div
                style={{
                    marginTop: 16,
                    marginBottom: data?.modifyPwdSafetyCode ? '68px' : '215px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'flex-end'
                }}
            >
                <Button type="primary" style={{ width: '100%' }} loading={submitLoading} onClick={handleSubmit}>
                    设置密码，前往登录
                </Button>
            </div>
        </div>
    );
    return (
        <div className={styles.interviewPc}>
            <Spin spinning={loading}>
                <InterviewBoxPcB
                    titleProps={{
                        src: data?.modifyPwdSafetyCode ? pic : picLogin,
                        // titleAfter: companyName,
                        title,
                        content,
                        picStyle: { marginBottom: 24, marginLeft: data?.modifyPwdSafetyCode ? 22 : 138 },
                        showStep: false,
                        wrap: true
                    }}
                    showLeftRight={data?.modifyPwdSafetyCode}
                    left={data?.modifyPwdSafetyCode ? renderLeftView() : null}
                    right={data?.modifyPwdSafetyCode ? renderRightView() : null}
                    leftStyle={data?.modifyPwdSafetyCode ? { width: '49%' } : {}}
                    rightStyle={data?.modifyPwdSafetyCode ? { width: '49%' } : {}}
                >
                    <div style={{ width: 392, boxSizing: 'borderBox', margin: '0 auto' }}>
                        <div style={{ marginTop: '163px' }}>
                            <InterviewDetail
                                style={{ padding: 0, margin: 0 }}
                                dataSource={[
                                    {
                                        key: '账号',
                                        showIcon: false,
                                        render: (
                                            <span
                                                style={{
                                                    display: 'block',
                                                    marginBottom: '8px',
                                                    height: '24px',
                                                    lineHeight: '24px',
                                                    fontSize: 16,
                                                    fontFamily: 'PingFangSC-Regular, PingFang SC',
                                                    fontWeight: 400,
                                                    color: 'rgba(0,0,0,0.65)'
                                                }}
                                            >
                                                <div style={{ whiteSpace: 'pre', display: 'inline-block' }}>账号：</div>
                                            </span>
                                        ),
                                        value: (
                                            <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                                <Popover
                                                    placement="right"
                                                    content={
                                                        <div
                                                            style={{
                                                                width: 210,
                                                                boxSizing: 'border-box',
                                                                display: 'flex'
                                                            }}
                                                        >
                                                            <Icon
                                                                type="close-circle"
                                                                theme="filled"
                                                                style={{
                                                                    marginRight: '4px',
                                                                    color: '#F55656',
                                                                    paddingTop: '4px'
                                                                }}
                                                            />
                                                            <div>
                                                                {form.getFieldError('talentEmail')
                                                                    ? form.getFieldError('talentEmail')[0]
                                                                    : ''}
                                                            </div>
                                                        </div>
                                                    }
                                                    visible={!!form.getFieldError('talentEmail')}
                                                >
                                                    {getFieldDecorator('talentEmail', {
                                                        initialValue: data?.talentEmail || 'chenyanhua@vv.cn',
                                                        rules: [
                                                            {
                                                                required: true,
                                                                whiteSpace: true,
                                                                message: '请输入邮箱'
                                                            },
                                                            {
                                                                validator(rule, value, callback) {
                                                                    const regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                                                                    if (value) {
                                                                        const tempValue = value.trim();
                                                                        if (regex.test(tempValue)) {
                                                                            callback();
                                                                        } else {
                                                                            callback('请输入正确的个人邮箱');
                                                                        }
                                                                    }
                                                                    callback();
                                                                }
                                                            }
                                                        ]
                                                    })(<Input placeholder="请输入邮箱" disabled />)}
                                                </Popover>
                                            </Form.Item>
                                        )
                                    }
                                ]}
                            />
                            <InterviewDetail
                                popTip={false}
                                style={{ padding: 0, margin: 0 }}
                                dataSource={[
                                    {
                                        key: '密码',
                                        showIcon: false,
                                        render: (
                                            <span
                                                style={{
                                                    display: 'block',
                                                    marginBottom: '8px',
                                                    height: '24px',
                                                    lineHeight: '24px',
                                                    fontSize: 16,
                                                    fontFamily: 'PingFangSC-Regular, PingFang SC',
                                                    fontWeight: 400,
                                                    color: 'rgba(0,0,0,0.65)'
                                                }}
                                            >
                                                <div style={{ whiteSpace: 'pre', display: 'inline-block' }}>密码：</div>
                                            </span>
                                        ),
                                        value: (
                                            <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                                <Popover
                                                    placement="right"
                                                    content={
                                                        <div
                                                            style={{
                                                                width: 210,
                                                                boxSizing: 'border-box',
                                                                display: 'flex'
                                                            }}
                                                        >
                                                            <Icon
                                                                type="close-circle"
                                                                theme="filled"
                                                                style={{
                                                                    marginRight: '4px',
                                                                    color: '#F55656',
                                                                    paddingTop: '4px'
                                                                }}
                                                            />
                                                            <div>
                                                                {form.getFieldError('password')
                                                                    ? form.getFieldError('password')[0]
                                                                    : ''}
                                                            </div>
                                                        </div>
                                                    }
                                                    visible={false}
                                                >
                                                    {getFieldDecorator('password', {
                                                        rules: [
                                                            {
                                                                required: true,
                                                                whiteSpace: true,
                                                                message: '请输入密码！'
                                                            },
                                                            {
                                                                validator(rule, value, callback) {
                                                                    if (value) {
                                                                        const regex = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).*$/;
                                                                        const tempValue = value.trim();
                                                                        if (data?.modifyPwdSafetyCode) {
                                                                            if (
                                                                                tempValue.length >= 8 &&
                                                                                tempValue.length <= 20 &&
                                                                                regex.test(value)
                                                                            ) {
                                                                                callback();
                                                                            } else {
                                                                                callback(
                                                                                    '长度为8-20个字符，需同时包含大小写字母及数字'
                                                                                );
                                                                            }
                                                                        } else if (
                                                                            tempValue.length < 8 &&
                                                                            tempValue.length > 0
                                                                        ) {
                                                                            callback('密码长度不少于 8 个字符！');
                                                                        }
                                                                    }

                                                                    callback();
                                                                }
                                                            }
                                                        ]
                                                    })(
                                                        <InputPassword
                                                            placeholder="请输入密码"
                                                            minLength={8}
                                                            maxLength={20}
                                                            allowClear
                                                        />
                                                    )}
                                                </Popover>
                                            </Form.Item>
                                        )
                                    }
                                ]}
                            />
                            {needAuthCode && (
                                <Spin spinning={codeLoading}>
                                    <InterviewDetail
                                        style={{ padding: 0, margin: 0 }}
                                        dataSource={[
                                            {
                                                key: '验证码',
                                                showIcon: false,
                                                render: (
                                                    <span
                                                        style={{
                                                            display: 'block',
                                                            marginBottom: '8px',
                                                            height: '24px',
                                                            lineHeight: '24px',
                                                            fontSize: 16,
                                                            fontFamily: 'PingFangSC-Regular, PingFang SC',
                                                            fontWeight: 400,
                                                            color: 'rgba(0,0,0,0.65)'
                                                        }}
                                                    >
                                                        <div style={{ whiteSpace: 'pre', display: 'inline-block' }}>
                                                            验证码：
                                                        </div>
                                                    </span>
                                                ),
                                                value: (
                                                    <Form.Item label="" colon={false} className={styles.formItemWrap}>
                                                        <Popover
                                                            placement="right"
                                                            content={
                                                                <div
                                                                    style={{
                                                                        width: 210,
                                                                        boxSizing: 'border-box',
                                                                        display: 'flex'
                                                                    }}
                                                                >
                                                                    <Icon
                                                                        type="close-circle"
                                                                        theme="filled"
                                                                        style={{
                                                                            marginRight: '4px',
                                                                            color: '#F55656',
                                                                            paddingTop: '4px'
                                                                        }}
                                                                    />
                                                                    <div>
                                                                        {form.getFieldError('verificationValue')
                                                                            ? form.getFieldError('verificationValue')[0]
                                                                            : ''}
                                                                    </div>
                                                                </div>
                                                            }
                                                            visible={!!form.getFieldError('verificationValue')}
                                                        >
                                                            <Row gutter={12}>
                                                                <Col span={16}>
                                                                    {getFieldDecorator('verificationValue', {
                                                                        rules: [
                                                                            {
                                                                                required: true,
                                                                                whiteSpace: true,
                                                                                message: '请输入验证码'
                                                                            }
                                                                        ]
                                                                    })(<Input placeholder="请输入验证码" />)}
                                                                </Col>
                                                                <Col span={8}>
                                                                    <img
                                                                        alt=""
                                                                        src={`data:image/png;base64, ${authCode}`}
                                                                        style={{ width: '100%' }}
                                                                        onClick={() => getAuthCode()}
                                                                    />
                                                                </Col>
                                                            </Row>
                                                        </Popover>
                                                    </Form.Item>
                                                )
                                            }
                                        ]}
                                    />
                                </Spin>
                            )}
                        </div>

                        <div
                            style={{
                                marginTop: 16,
                                marginBottom: data?.modifyPwdSafetyCode ? '68px' : '215px',
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'flex-end'
                            }}
                        >
                            <Button
                                type="primary"
                                style={{ width: '100%' }}
                                loading={handleloading?.loading}
                                onClick={handleSubmit}
                            >
                                登录
                            </Button>

                            <a
                                onClick={() => {
                                    history.push({
                                        pathname: '/external/interview/resetPassword',
                                        query: {
                                            id: query?.id,
                                            name: data?.talentName,
                                            email: data?.talentEmail
                                        }
                                    });
                                }}
                                style={{
                                    textAlign: 'right',
                                    color: 'rgba(0,0,0,0.85)',
                                    fontSize: '14px',
                                    fontWeight: 400,
                                    lineHeight: '26px',
                                    marginTop: '11px'
                                }}
                            >
                                忘记密码？
                            </a>
                        </div>
                    </div>
                </InterviewBoxPcB>
            </Spin>
        </div>
    );
};

export default withRouter(Form.create({})(Login));
